package com.reny.ll.git.mvvm.extras

import androidx.annotation.AnyThread
import androidx.annotation.MainThread
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.kunminx.architecture.ui.callback.ProtectedUnPeekLiveData

class LifecycleJvm {
    companion object {
        @JvmStatic
        fun <T> observe(owner: LifecycleOwner, liveData: LiveData<T>, observer: Observer<T>){
            try {
                liveData.observe(owner, object :Observer<T>{
                    override fun onChanged(t: T) {
                        observer.onChanged(t)
                    }
                })
            }catch (e: Exception){}
        }
    }
}


//不要直接使用 liveData.observe 防止一些错误 Observer的创建最好不要不lamda 表达式
fun <T> LifecycleOwner.observe(liveData: LiveData<T>?, observer: (t: T) -> Unit) {
    if(liveData == null) return
    liveData.observe(this, object :Observer<T>{
        override fun onChanged(t: T) {
            observer(t)
        }
    })
}

fun <T> LifecycleOwner.observeUnPeek(liveData: ProtectedUnPeekLiveData<T>, observer: (t: T) -> Unit) {
    liveData.observe(this, object :Observer<T>{
        override fun onChanged(t: T) {
            observer(t)
        }
    })
}


@AnyThread
inline fun <reified T> MutableLiveData<T>.postNext(map: (T) -> T) {
    postValue(map(verifyLiveDataNotEmpty()))
}

@MainThread
inline fun <reified T> MutableLiveData<T>.setNext(map: (T) -> T) {
    value = map(verifyLiveDataNotEmpty())
}

@AnyThread
inline fun <reified T> LiveData<T>.verifyLiveDataNotEmpty(): T {
    return value
        ?: throw NullPointerException("MutableLiveData<${T::class.java}> not contain value.")
}
